package controller

import (
	"blog2021/model"
	"blog2021/tools/util"
	"net/http"
	"unicode"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

type RespData struct {
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
	Content string `json:"content"`
}

func ResponseMessage(c *gin.Context, title string, message string) {
	c.HTML(http.StatusInternalServerError, "response.html", gin.H{
		"content": gin.H{
			"Title":   title,
			"Message": message,
		},
		"token": CurrentToken(c),
	})
}

func GetReferer(c *gin.Context) string {
	refererList := c.Request.Header["Referer"]
	if refererList != nil && len(refererList) > 0 {
		return refererList[0]
	}
	return "/"
}

func CurrentUser(c *gin.Context) model.User {
	token := CurrentToken(c)
	if len(token) > 0 {
		if user, err := model.GetUserFromToken(token); err == nil {
			user.Password = ""
			return user
		}
	}
	return model.User{}
}

func CurrentToken(c *gin.Context) string {
	session := sessions.Default(c)
	if token := session.Get("token"); token != nil {
		return token.(string)
	}
	return ""
}

func PostContent2Profile(content string) string {
	const MaxProfileCount = 200
	profileCount := 0
	profile := make([]rune, 0, MaxProfileCount+3)
	for _, a := range content {
		if a != '*' && a != '#' && a != '|' && a != '`' {
			profile = append(profile, a)
			profileCount = profileCount + util.If(unicode.Is(unicode.Han, a), 2, 1).(int)
			if profileCount >= MaxProfileCount {
				break
			}
		}
	}
	return string(profile) + "..."
}

func GetType(t string) int {
	if t == "译" {
		return 1
	} else if t == "转" {
		return 2
	} else {
		return 0
	}
}
